import type { Ref } from 'vue'
import { ref } from 'vue'

/**
 * 倒计时 Hook
 * @param duration 倒计时时间（秒），默认 60
 * @param autoStart 是否自动开始
 * @returns { countDown, isRunning, start, stop, reset }
 */
export function useCountDown(duration: number = 60, autoStart: boolean = false): {
  countDown: Ref<number>
  isRunning: Ref<boolean>
  start: () => void
  stop: () => void
  reset: (newDuration?: number) => void
} {
  const countDown = ref<number>(duration)
  const isRunning = ref<boolean>(false)
  let timer: ReturnType<typeof setInterval> | null = null

  const start = (): void => {
    if (isRunning.value)
      return
    isRunning.value = true
    timer = setInterval(() => {
      if (countDown.value > 0) {
        countDown.value--
      }
      else {
        stop()
      }
    }, 1000)
  }

  const stop = (): void => {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    isRunning.value = false
  }

  const reset = (newDuration?: number): void => {
    stop()
    countDown.value = newDuration ?? duration
  }

  if (autoStart) {
    start()
  }

  return {
    countDown,
    isRunning,
    start,
    stop,
    reset,
  }
}
